package com.lanou3g.zjl.chating.home.friends;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseActivity;
import com.lanou3g.zjl.chating.home.personal_center.CircleImageView;
import com.lanou3g.zjl.chating.utils.GetUserAvatarHelper;
import com.lanou3g.zjl.chating.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemLongClick;

/**
 * Created by dllo on 15/11/26.
 */
public class GroupMembersActivity extends BaseActivity {
    private String groupId;//群id
    private Handler handler;
    private EMGroup group;//群对象
    private MembersListAdapter adapter;
    private boolean isOwner;
    private boolean isAllowInvit;
    private List<String> membersList;
    @Bind(R.id.groupMemberList)
    ListView groupMemberList;
    @Bind(R.id.invitIntoGroup)
    TextView invitIntoGroup;
    private List<GroupItem> groupItems;

    private class GroupItem{
        String name;
        String headIcon;

        public GroupItem(String name) {
            this.name = name;
        }

        public String getHeadIcon() {
            return headIcon;
        }

        public void setHeadIcon(String headIcon) {
            this.headIcon = headIcon;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }


    @Override
    protected int getLayout() {

        return R.layout.group_members_activity;
    }

    @OnClick(R.id.invitIntoGroup)
    void gotoInvitFriends() {
        Intent intent = new Intent(GroupMembersActivity.this, InvitFriendsIntoGroupActivity.class);
        intent.putExtra("ID", groupId);
        startActivity(intent);
    }

    @Override
    protected void initData() {


    }

    @OnClick(R.id.finishGorupMember)
    void finishGorupMember() {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        groupId = getIntent().getStringExtra("Id");
        getGroupInfo(groupId);
        getAsynk();
    }

    //删除群成员或移到黑名单
    @OnItemLongClick(R.id.groupMemberList)
    boolean deleteFriends(final int positon, View view) {
        if (isOwner && !adapter.getItem(positon).equals(EMChatManager.getInstance().getCurrentUser())) {
            PopupMenu popupMenu = new PopupMenu(this, view);
            popupMenu.getMenuInflater().inflate(R.menu.delete_group_members, popupMenu.getMenu());
            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                        case R.id.deleteGroupMembers:
                            deleteGroupMembers(adapter.getItem(positon));
                            break;
                        case R.id.moveToBlackList:
                            moveToBlackList(adapter.getItem(positon));
                            break;
                    }
                    return true;
                }
            });
            popupMenu.show();
        }
        return false;
    }

    //获取子线程发送的消息
    private void getAsynk() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 1:
                        //如果不是群主而且不允许群成员邀请好友则隐藏邀请按钮
                        if (!isOwner && !isAllowInvit) {
                            invitIntoGroup.setVisibility(View.GONE);
                        }
                        adapter = new MembersListAdapter();
                        //当群对象获取成功之后设置相应的值
                        groupMemberList.setAdapter(adapter);
                        break;
                    case 2:
                        //刷新
                        getGroupInfo(groupId);
                        Toast.makeText(GroupMembersActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        //刷新
                        getGroupInfo(groupId);
                        Toast.makeText(GroupMembersActivity.this, "已成功移到黑名单", Toast.LENGTH_SHORT).show();
                        break;
                }
                return false;
            }
        });
    }

    //根据群id去服务器得到该群的详细信息
    private void getGroupInfo(final String groupId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    group = EMGroupManager.getInstance().getGroupFromServer(groupId);

                    if (group != null) {
                        if (group.getOwner().equals(EMChatManager.getInstance().getCurrentUser())) {
                            isOwner = true;
                        } else {
                            isOwner = false;
                        }
                        if (group.isAllowInvites()) {
                            isAllowInvit = true;
                        } else {
                            isAllowInvit = false;
                        }
                        membersList = group.getMembers();

                        groupItems = new ArrayList<GroupItem>();
                        for(String s:membersList){
                            groupItems.add(new GroupItem(s));
                        }
                        handler.sendEmptyMessage(1);
                    }
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //删除群成员方法
    private void deleteGroupMembers(final String name) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMGroupManager.getInstance().removeUserFromGroup(groupId, name);
                    handler.sendEmptyMessage(2);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //将群成员移到黑名单
    private void moveToBlackList(final String username) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMGroupManager.getInstance().blockUser(groupId, username);
                    handler.sendEmptyMessage(3);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public class MembersListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return membersList != null && membersList.size() > 0 ? membersList.size() : 0;
        }

        @Override
        public String getItem(int i) {
            return membersList != null && membersList.size() > 0 ? membersList.get(i) : null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, final ViewGroup viewGroup) {
            ViewHolder holder = null;
            String name = getItem(i);

            if (view == null) {
                view = LayoutInflater.from(GroupMembersActivity.this).inflate(R.layout.members_listitem, null);
                holder = new ViewHolder(view);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.groupMemberName.setText(name);

            Handler handler= new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                    String url = (String) message.obj;
                    groupItems.get(i).setHeadIcon(url);
                    notifyDataSetChanged();
//                    VolleySingleton.getInstance(viewGroup.getContext()).getPic(url, finalHolder.groupMemberPic);//前台进行头像设置
                    return false;
                }
            });

            if (groupItems.get(i).getHeadIcon() != null && groupItems.get(i).getHeadIcon().length() > 0){
                VolleySingleton.getInstance(viewGroup.getContext()).getPic(groupItems.get(i).getHeadIcon(), holder.groupMemberPic);//前台进行头像设置
            }
            else
            {
                holder.groupMemberPic.setImageResource(R.mipmap.default_head);
            }

            GetUserAvatarHelper helper = new GetUserAvatarHelper(GroupMembersActivity.this,handler);
            helper.execute(name);

//            GetUserAvatarHelper helper = new GetUserAvatarHelper(GroupMembersActivity.this, holder.groupMemberPic, groupItems.get(i).getName());
//            helper.execute(groupItems.get(i).getName());
            return view;
        }

        class ViewHolder {
            @Bind(R.id.groupMemberPic)
            CircleImageView groupMemberPic;
            @Bind(R.id.groupMemberName)
            TextView groupMemberName;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }
}
